package com.example.hqpatrol.fragment;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.hqpatrol.MainActivity;
import com.example.hqpatrol.R;
//import com.example.hqpatrol.base.BaseFragment;
import com.example.hqpatrol.adapter.PatrolListAdapter;
import com.example.hqpatrol.base.BaseFragment;
import com.example.hqpatrol.common.util.GsonUtil;
import com.example.hqpatrol.common.util.WidgetUtils;
import com.example.hqpatrol.databinding.FragmentDropDownMenuBinding;
import com.example.hqpatrol.databinding.FragmentPatrolReadyBinding;
import com.example.hqpatrol.entity.patrol.PatrolPage;
import com.example.hqpatrol.entity.patrol.PatrolSimple;
import com.example.hqpatrol.entity.reequest.PatrolRequestParams;
import com.example.hqpatrol.entity.response.PatrolResponse;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.scwang.smartrefresh.header.DeliveryHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.SnackbarUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.DialogLoader;
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText;
import com.xuexiang.xui.widget.spinner.DropDownMenu;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xutil.app.FragmentUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;

@Page
//public class PatrolReadyFragment extends BaseFragment<FragmentPatrolReadyBinding> { //这里改为使用下拉菜单的fragment，然后配置视图内容为巡检列表的视图
public class PatrolReadyFragment extends BaseFragment<FragmentDropDownMenuBinding> {

    //顶部搜索栏
    private DropDownMenu top_drop_down_menu;
    //巡检列表顶级主视图
    private RelativeLayout relativeLayout;
    //填充巡检列表的视图
    private RecyclerView patrol_item_recycler_view;
    //上拉下拉刷新
    private SmartRefreshLayout refresh_layout;
    //状态图标填充
    private StatefulLayout patrol_full_state_layout;
    //每个巡检卡片的布局adapter
    private PatrolListAdapter patrolListAdapter;

    //网络请求接口数据的参数
    private PatrolRequestParams patrolRequestParams;
    //共有多少条
    private Integer totalCount = 0;
    //搜索参数
    private String patrolObjectSearch;
    private String unitNameSearch;

    @NonNull
    @Override
    protected FragmentDropDownMenuBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentDropDownMenuBinding.inflate(inflater, container, false);
    }

    @Override
    protected TitleBar initTitle() {
        return null;
    }

    @Override
    protected void initViews() {
        initComponent();
        initList();
        initDropDown();
    }

    @Override
    protected void initListeners() {

    }

    public void onShowPage(){
        System.out.println("onShowPage============");
    }

    private void initComponent() {
        relativeLayout = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.fragment_patrol_ready, null);
        patrol_item_recycler_view = relativeLayout.findViewById(R.id.recycler_view);

        refresh_layout = relativeLayout.findViewById(R.id.refresh_layout);
        refresh_layout.setRefreshHeader(new DeliveryHeader(getContext()));

        patrol_full_state_layout = relativeLayout.findViewById(R.id.patrol_full_state_layout);

        patrolRequestParams = new PatrolRequestParams();
        patrolRequestParams.setCode("DS");
        patrolRequestParams.setStep("0");
    }

    private void initList() {
        WidgetUtils.initRecyclerView(patrol_item_recycler_view, 0);
        patrol_item_recycler_view.setAdapter(patrolListAdapter = new PatrolListAdapter());
        refresh_layout.setEnableAutoLoadMore(true);
        refresh_layout.setOnRefreshListener(refreshLayout -> {
            patrolRequestParams.setPage(1);
            onRefreshPatrolList(refreshLayout);
        });
        refresh_layout.setOnLoadMoreListener(refreshLayout -> {
            patrolRequestParams.setPage(patrolRequestParams.getPage() + 1);
            onLoadMorePatrolList(refreshLayout);
        });

        //巡检项点击事件
        patrolListAdapter.setOnItemClickListener(this::onPatrolClickListener);

        // 触发自动刷新
        refresh_layout.autoRefresh();

    }

    //点击搜索切换搜索下拉框的显示隐藏
    public void toggleSearchDropDown() {
        if(top_drop_down_menu.getChildAt(0).getVisibility() == View.GONE){
            top_drop_down_menu.getChildAt(0).setVisibility(View.VISIBLE);
        }else{
            top_drop_down_menu.getChildAt(0).setVisibility(View.GONE);
        }
    }

    //顶部搜索栏
    private void initDropDown() {
        top_drop_down_menu = findViewById(R.id.ddm_content);
        String[] dropDownMenuHeaders = new String[]{"巡检对象", "单位名称"};

        //巡检对象
        View patrolObjectView = LayoutInflater.from(getContext()).inflate(R.layout.layout_drop_down_patrol_object, null);
        Button objectButton = patrolObjectView.findViewById(R.id.btn_ok);
        MaterialEditText objectText = patrolObjectView.findViewById(R.id.text_text);
        objectButton.setOnClickListener(v -> {
            top_drop_down_menu.closeMenu();
            String newPatrolObjectSearch = Convert.toStr(objectText.getText());
            if(!StrUtil.equals(patrolObjectSearch, newPatrolObjectSearch)){
                patrolObjectSearch = newPatrolObjectSearch;
                patrolRequestParams.setPatrolObject(patrolObjectSearch);
                refresh_layout.autoRefresh();
            }
        });

        //单位名称
        View unitNameView = LayoutInflater.from(getContext()).inflate(R.layout.layout_drop_down_patrol_object, null);
        MaterialEditText unitNameText = unitNameView.findViewById(R.id.text_text);
        unitNameText.setHint("请输入单位名称");
        Button unitNameButton = unitNameView.findViewById(R.id.btn_ok);
        unitNameButton.setOnClickListener(v -> {
            top_drop_down_menu.closeMenu();
            String newUnitNameSearch = Convert.toStr(unitNameText.getText());
            if(!StrUtil.equals(unitNameSearch, newUnitNameSearch)){
                unitNameSearch = newUnitNameSearch;
                patrolRequestParams.setUnitName(unitNameSearch);
                refresh_layout.autoRefresh();
            }
        });

        List<View> viewList = new ArrayList<>();
        viewList.add(patrolObjectView);
        viewList.add(unitNameView);
        LinearLayout contentView = new LinearLayout(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.addView(relativeLayout);
        top_drop_down_menu.setDropDownMenu(dropDownMenuHeaders, viewList, contentView);
        top_drop_down_menu.getChildAt(0).setVisibility(View.GONE);
    }

    //上拉加载更多
    private void onLoadMorePatrolList(RefreshLayout refreshLayout) {
        Map<String, Object> params = GsonUtil.beanToMap(patrolRequestParams);
        XHttp.get("https://www.shhanqian.com:18022/core/patrol/list").syncRequest(false).onMainThread(true).params(params).execute(new CallBackProxy<PatrolResponse<PatrolPage>, PatrolPage>(new SimpleCallBack<PatrolPage>() {
            @Override
            public void onSuccess(PatrolPage response) throws Throwable {
                List<Map<String, Object>> patrolSimpleListMap = response.getList();
                List<PatrolSimple> patrolSimpleList = new ArrayList<>();
                patrolSimpleListMap.forEach(map -> patrolSimpleList.add(GsonUtil.getInstance().fromJson(GsonUtil.getInstance().toJson(map), PatrolSimple.class)));
                patrolListAdapter.loadMore(patrolSimpleList);
                if(response.getTotalPage() <= patrolRequestParams.getPage()){
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }else{
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onError(ApiException e) {
                e.printStackTrace();
                patrol_full_state_layout.showError(v -> refreshLayout.autoRefresh());
                refreshLayout.setEnableLoadMore(false);
                SnackbarUtils.Short(getView(), "调用远程接口失败").danger().show();
            }
        }){});
    }

    //下拉刷新
    private void onRefreshPatrolList(RefreshLayout refreshLayout) {
        Log.d("dong", "开始刷新获取接口数据");
        refreshLayout.setEnableLoadMore(true);
        Map<String, Object> params = GsonUtil.beanToMap(patrolRequestParams);
        XHttp.get("https://www.shhanqian.com:18022/core/patrol/list").syncRequest(false).onMainThread(true).params(params).execute(new CallBackProxy<PatrolResponse<PatrolPage>, PatrolPage>(new SimpleCallBack<PatrolPage>() {
            @Override
            public void onSuccess(PatrolPage response) throws Throwable {
                List<Map<String, Object>> patrolSimpleListMap = response.getList();
                if(patrolRequestParams.getPage() == 1 && patrolSimpleListMap.size() == 0){
                    patrol_full_state_layout.showEmpty();
                    refreshLayout.finishRefresh();
                    refreshLayout.setEnableLoadMore(false);
                }else{
                    patrol_full_state_layout.showContent();
                    List<PatrolSimple> patrolSimpleList = new ArrayList<>();
                    patrolSimpleListMap.forEach(map -> patrolSimpleList.add(GsonUtil.getInstance().fromJson(GsonUtil.getInstance().toJson(map), PatrolSimple.class)));
                    patrolListAdapter.refresh(patrolSimpleList);
                    refreshLayout.finishRefresh();
                    refreshLayout.resetNoMoreData();
                }

                //设置待巡检菜单角标
                totalCount = Convert.toInt(response.getTotalCount());
                updateTotalCount();
            }

            @Override
            public void onError(ApiException e) {
                e.printStackTrace();
                patrol_full_state_layout.showError(v -> refreshLayout.autoRefresh());
                refreshLayout.finishRefresh();
                refreshLayout.resetNoMoreData();
                refreshLayout.setEnableLoadMore(false);
                SnackbarUtils.Short(getView(), "调用远程接口失败").danger().show();
            }
        }){});
    }

    //点击一个待巡检项
    private void onPatrolClickListener(View itemView, PatrolSimple item, int position) {
        Log.d("dong", item.getPatrolObject());
        Bundle params = new Bundle();
        params.putLong(PatrolInputFragment.BUNDLE_KEY_ID, item.getId());
        params.putString(PatrolInputFragment.BUNDLE_KEY_TITLE, item.getPlanPatrolTopic());
        params.putInt(PatrolInputFragment.BUNDLE_KEY_POSITION, position);
        openNewPage(PatrolInputFragment.class, params);
    }

    //从广播接受
    public void removeItem(Intent intent) {
        if(intent != null && intent.getExtras() != null){
            Bundle bundle = intent.getExtras();
            boolean isFinished = bundle.getBoolean("isFinished", false);
            int position = bundle.getInt(PatrolInputFragment.BUNDLE_KEY_POSITION, -1);
            System.out.println(position);
            if(isFinished && position >= 0){
                patrolListAdapter.delete(position);
                SnackbarUtils.Short(getView(), "移除了一项index：" + position).confirm().show();
                totalCount--;
                updateTotalCount();
            }
        }
    }

    //更新主页待巡检数，和底部菜单栏角标
    private void updateTotalCount() {
        MainActivity.badge_ready.setBadgeNumber(totalCount);
        MainActivity.patrolHomeFragment.updateReadyCount(Convert.toStr(totalCount));
    }

}